import { DataBase, DataStructure } from "./database";
import { DeviceMode } from "./deviceMode";


export interface DeviceListInfo {
    deviceId: string;
    deviceModel: string;
    mainFirmVer: string;
    modelCode: string;
    publicKey: string;
}

/** 设备列表 */
export class DeviceList extends DataBase {
    public static collectionName: string = "DeviceList";
    /** 全局 */
    public static globalDeviceList: DeviceList;
    /** 设备名称 */
    public name: string;
    /** 设备型号 */
    public modeId: string;
    /** 设备分组ID */
    public groupId: string;
    /** 设备信息 */
    public info: DeviceListInfo;
    /** 轮播信息 */
    public carouselText: string;
    /** 来自腾讯云获取的设备信息描述 */
    public describeDeviceInfo?: DescribeDeviceInfo;

    constructor(data: DataStructure = {}) {
        super(data);
        this.name = data['name'] || "";
        this.modeId = data['modeId'] || "";
        this.groupId = data['groupId'] || "";
        this.carouselText = data['carouselText'] || "";
        this.info = data['info']

    }

    /** 获取所有设备列表 */
    public static async GetDeviceList(groupId: string) {
        const a = await this.GetAllData({
            _openid: '{openid}',
            groupId: groupId
        });
        return a.map(x => new DeviceList(x));
    }
    /** 使用_id获取设备信息 */
    public static async GetDeviceListDoc(_id: string, groupId: string) {
        const a = await this.GetAllData({
            _openid: '{openid}',
            groupId: groupId,
            _id: _id
        });
        a.map(x => new DeviceList(x));
        return a[0];
    }
    /**
     * 创建一个设备
     * @param name 
     * @param modeId 
     * @param groupId 
     */
    public static async CreateDevice(name: string, modeId: string, groupId: string, info: Object) {
        const a = await this.AddData(new DeviceList({
            name,
            modeId,
            groupId,
            info: info
        }))
        return a
    }


    public searchDeviceMode(deviceMode: DeviceMode[]) {
        for (let i = 0; i < deviceMode.length; i++) {
            const e = deviceMode[i];
            if (this.modeId === e.get_id()) {
                return e
            }
        }
        throw new Error("没找到相关的DeviceMode");
    }

    public async remove() {
        return await DeviceList.RemoveDataInWhere({
            _id: this.get_id(),
            groupId: this.groupId,
        })
    }


    public async saveName(name: string) {
        this.name = name;
        return await DeviceList.UpdateDataInWhere2({
            name: name
        }, {
            _id: this.get_id(),
            groupId: this.groupId,
        })
    }
}